<?php


class Apilogin extends ApiBase {

	//授权登录
	private $token;
	private $appId;
	private $appSecret;

	public function __construct(){
		parent::__construct();
		$info=$this->db->get('wxapp')->row_array();
		$this->appId=$info['AppID'];
		$this->appSecret=$info['AppSecret'];
	}

	public function login(){
		$post=$this->input->post();
		//微信登录 获取session_key
		$session = $this->wxlogin($post['code']);
		unset($post['code']);
		$post['openid']=$session['openid'];
		// 自动注册用户
		$user_id = $this->register($post);
		// 生成token (session3rd)
		$this->token = $this->token($post['openid']);
		$post['user_id']=$user_id;
		// 记录缓存, 7天
		$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
		$this->cache->save($this->token, $post,86400*7);
		$this->show(array('code'=>1,'user_id'=>$user_id,'token'=>$this->token));

	}

	/**
	 * 微信登录
	 * @param $code
	 * @return array|mixed
	 * @throws BaseException
	 * @throws \think\exception\DbException
	 */
	private function wxlogin($code){
		// 获取当前小程序信息
		if ($this->appId=="" || $this->appSecret=="") {
			$this->show(array('code'=>-1,'msg'=>'请到[小程序-参数设置] 填写appid和appSecret'));
		}
		// 微信登录 (获取session_key)
		$url = 'https://api.weixin.qq.com/sns/jscode2session?';
		$url.= 'appid='.$this->appId.'&secret='.$this->appSecret.'&js_code='.$code.'&grant_type=authorization_code';
		$result = json_decode($this->curlget($url),true);

		if (isset($result['errcode'])) {
			$this->show(array('code'=>-1,'msg'=>$result['errmsg']));
		}

		return $result;
	}



	/**
	 * 生成用户认证的token
	 * @param $openid
	 * @return string
	 */
	private function token($openid){
		return md5($openid . 'token_salt');
	}


	/**
	 * 自动注册用户
	 */
	private function register($post){
		$post['nickName'] = preg_replace('/[\xf0-\xf7].{3}/', '', $post['nickName']);
		$check=$this->db->where('openid',$post['openid'])->get('user')->row_array();
		if($check){
			$post['update_time']=time();
			$this->db->update('user', $post,array('user_id'=>$check['user_id']));
			return (int)$check['user_id'];
		}else{
			$post['create_time']=time();
			$post['update_time']=time();
			$this->db->insert('user', $post);
			$user_id=$this->db->insert_id();
			if ($user_id<1) {
			$this->show(array('code'=>-1,'msg'=>'用户注册失败'));
			}
			return $user_id;

		}
	}


	/**
	 * 模拟GET请求 HTTPS的页面
	 * @param string $url 请求地址
	 * @return string $result
	 */
	public function curlget($url){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}

}
